<?php
/**
 * User: hjd-yao
 * Date: 2019/6/12
 * Time: 17:19
 */

namespace Shop\Http\Controllers\Wap;


use App\Helpers\CreateQrCode;
use App\Helpers\SelfResponse;
use App\Models\Bonus\BonusCountModel;
use App\Models\User\AccountFlowModel;
use App\User\UserCenter;
use DC\BonusCenter\Services\ShoppingBonus;
use DC\UserCenter\Models\UserAuthModel;
use DC\UserCenter\Models\UserInfoModel;
use DC\UserCenter\Models\UserWalletModel;
use DC\UserCenter\Services\UserRegister;
use Frontend\Http\Requests\RegisterRequest;
use Frontend\Models\UserBaseModel;
use App\Helpers\SendSMS;
use Illuminate\Http\Request;
use Shop\Http\Controllers\BaseController;
use Shop\Http\Requests\UpdateInfoRequest;
use Shop\Http\Requests\UpdatePwdRequest;
use App\Models\Bonus\BonusRecordModel;
use DC\BonusCenter\Services\RegBonus;

class UserController extends BaseController
{

    public function qiandao(Request $request)
    {
        $user_id = $request->input('user_id');
//        return SelfResponse::success('操作成功');
        $shop_api=new ShoppingBonus();
        $res=$shop_api->money_qiandao($user_id);
        if($res){
            return SelfResponse::success('操作成功');
        }else{
            return SelfResponse::error('操作失败，当天次数已用完');
        }
    }

    public function index(Request $request)
    {
        //$res = SendSMS::make()->sendCode('16603851055','123456',config('sms.fg.TemplateId.code'));

        $remind = 0;

        $user_id = $request->input('user_id');
        $info = UserBaseModel::find($user_id);

        if($info['level']==0 && $info['is_active']==1){
            $bonus_record =BonusRecordModel::init()->where('target_uid',$user_id)->where('bonus_type',42)->where('bonus','>',0)->count();
            if($bonus_record == 0){
                $remind = 1;
            }
        }

        return $this->wapRender('user.index',[
            'page_title'=>'我的',
            'info'=>$info,
            'remind'=>$remind
        ]);
    }

    public function management(Request $request)
    {
        $user_id = $request->input('user_id');
        $info = UserBaseModel::find($user_id);
        return $this->wapRender('user.management',[
            'page_title'=>'财务管理',
            'info'=>$info
        ]);
    }

    public function myInfo(Request $request)
    {
        $user_id = $request->input('user_id');
        $info = UserBaseModel::find($user_id);
        return $this->wapRender('user.my_info',[
            'page_title'=>'个人信息',
            'info'=>$info
        ]);
    }

    public function shareCode(Request $request)
    {
        $user_id = $request->input('user_id');
        $info = UserBaseModel::find($user_id);
        $url = route('f_Login_register',['code'=>$info->referrer_code]);

        $code_url = CreateQrCode::make()->setCodeUrl($info->referrer_code)->getCodeUrl();
        if(!$code_url){
            $logo = asset('logo.png');
//            if($info->head_pic){
//                $logo = $info->head_pic;
//            }
            $code_url = CreateQrCode::make()->bindQrCode()
                ->setSize(150)->setMargin(0)
     //           ->mergeLogo($logo,0.2)
                ->createCode($url)
                ->storageCode($info->referrer_code)
                ->setCodeUrl($info->referrer_code)->getCodeUrl();
        }

        return $this->wapRender('user.share',[
            'page_title'=>'分享码',
            'info'=>$info,
            'code_url'=>$code_url,
            'url'=>$url,
        ]);
    }


    public function accountFlow(Request $request)
    {
        $user_id = $request->input('user_id');
        $money_type = $request->input('mt',2);
        $pageNum = $request->input('page_num',1);
        $list = AccountFlowModel::where('target_uid',$user_id)->where('status',1)
            ->where('money_type',$money_type)
            ->forPage($pageNum,20)->orderBy('created_at','desc')->get();
        return $this->wapRender('user.account_flow',[
            'page_title'=>'流水',
            'money_type'=>$money_type,
            'list'=>$list
        ]);
    }

    public function bonusCount(Request $request)
    {
        $user_id = $request->input('user_id');
        $pageNum = $request->input('page_num',1);
        $list = BonusCountModel::where('target_uid',$user_id)
            ->forPage($pageNum,20)->orderBy('created_at','desc')->get();
        return $this->wapRender('user.bonus_count',[
            'page_title'=>'奖金',
            'list'=>$list
        ]);
    }

    public function myTeam(Request $request)
    {
        $user_id = $request->input('user_id');
        $deep = $request->input('generation',1);
        $pageNum = $request->input('page_num',1);
        $info = UserBaseModel::find($user_id);
        $model = UserBaseModel::where('status','>=',0)
            ->whereRaw("FIND_IN_SET(?,`referrer_ids`)",[$user_id])
            ->where('tdeep','<=',$info->tdeep+$deep);
        //$total = $model->count();
        $total=UserBaseModel::where('status','>=',0)
            ->whereRaw("FIND_IN_SET(?,`referrer_ids`)",[$user_id])->count();
        $list = $model->orderBy('tdeep')->forPage($pageNum,20)->get();
        return $this->wapRender('user.my_team',[
            'page_title'=>'团队',
            'info'=>$info,
            'deep'=>$deep,
            'list'=>$list,
            'total'=>$total
        ]);

    }

    public function updatePwd(UpdatePwdRequest $request,$action='login')
    {
        if($request->isMethod('post')){
            $user_id = $request->input('user_id');
            $authModel = new UserAuthModel();
            if($action == 'safe'){
                $old_safe = $request->post('old_pay_pwd');
                $new_safe = $request->post('pay_pwd');
                if(!$authModel->checkSafePwd($old_safe,$user_id)){
                    return SelfResponse::error('原支付密码错误');
                }
                if(!$authModel->updateSafePwd($new_safe,$user_id)){
                    return SelfResponse::error($authModel->getErrorMsg('修改失败'));
                }
            }else{
                $old_login = $request->post('old_pwd');
                $new_login = $request->post('new_pwd');
                if(!$authModel->checkLoginPwd($old_login,$user_id)){
                    return SelfResponse::error('原登录密码错误');
                }
                if(!$authModel->updateLoginPwd($new_login,$user_id)){
                    return SelfResponse::error($authModel->getErrorMsg('修改失败'));
                }
                UserBaseModel::init()->logout();
            }
            return SelfResponse::success('修改成功','f_Wap_User_index');
        }else{
            return $this->wapRender('user.update_pwd',[
                'page_title'=>'修改密码'
            ]);
        }
    }

    public function updateInfo(UpdateInfoRequest $request)
    {
        $user_id = $request->input('user_id');
        if($request->isMethod('post')){
            $userService = new UserRegister();
            $res = $userService->editByUser($request->post(),$user_id);
            if(!$res['status']){
                return SelfResponse::error('完善资料失败');
            }
            return SelfResponse::success('完善资料成功','f_Wap_User_index');
        }else{
            $info = UserBaseModel::find($user_id);
            return $this->wapRender('user.update_info',[
                'page_title'=>'完善资料',
                'user'=>$info
            ]);
        }
    }

    public function updateCollection(UpdateInfoRequest $request)
    {
        $user_id = $request->input('user_id');
        if($request->isMethod('post')){
            $userService = new UserRegister();
            $res = $userService->editByUser($request->post(),$user_id);
            if(!$res['status']){
                return SelfResponse::error('完善信息失败');
            }
            return SelfResponse::success('完善信息成功','f_Wap_User_index');
        }else{
            $info = UserBaseModel::find($user_id);
            return $this->wapRender('user.update_collection',[
                'page_title'=>'收款信息',
                'user'=>$info
            ]);
        }
    }


    public function updateCertification(UpdateInfoRequest $request)
    {
        $user_id = $request->input('user_id');
        if($request->isMethod('post')){
            $userService = new UserRegister();
            $res = $userService->editByUser($request->post(),$user_id);
            if(!$res['status']){
                return SelfResponse::error('认证信息失败');
            }
            return SelfResponse::success('认证信息成功','f_Wap_User_index');
        }else{
            $info = UserBaseModel::find($user_id);
            return $this->wapRender('user.update_certification',[
                'page_title'=>'实名认证',
                'user'=>$info
            ]);
        }
    }

    // 注册会员

    public function AddUser(RegisterRequest $request){
        $user_id = $request->input('user_id');
        if($request->isMethod('post')){
            $phone_code = $request->post('phone_code');
            $mobile = $request->post('phone');
            $sendSMS = SendSMS::make();
            if(!$sendSMS->checkCode($phone_code,$mobile)){
                return SelfResponse::error($sendSMS->getErrorMsg('验证码错误'));
            }
            $registerService = new UserRegister();
            $res = $registerService->registerByUser($request);
            if(!$res['status']){
                return SelfResponse::error($res['errorMsg']);
            }
            return SelfResponse::success('注册成功','f_Wap_User_active_list');
        }else{
            $info = UserBaseModel::init()->find($user_id);
            return $this->wapRender('user.register',[
                'page_title'=>'注册',
                'user'=>$info
            ]);
        }

    }

    // 未激活会员列表
    public function ActiveUserList(Request $request){

        $user_id = $request->input('user_id');

        $pageNum = $request->input('page_num',1);

        $model = UserBaseModel::init()->where('bd_uid',$user_id)->where('status',0);

        $list = $model->forPage($pageNum,$this->perNum())->get();

        return $this->wapRender('user.active_users',[
            'page_title'=>'激活会员',
            'list'=>$list,
            'user_id'=>$user_id
        ]);
    }


    // 激活会员
    public function ActiveUser(Request $request){

        $user_id = $request->input('user_id');
        $no_user_id = $request->input('no_user_id');

        $user_center = new UserCenter();
        if($user_center->activatedByUser($no_user_id,$user_id)){
            return SelfResponse::success('激活成功','f_Wap_User_active_list');
        }
        return SelfResponse::error($user_center->getErrorMsg('激活失败,请稍后再试！'));

    }

    // 删除会员
    public function removeUser(Request $request){

        $user_ids = $request->input('no_user_id');

        $user_ids = array_filter(is_array($user_ids)?$user_ids:str2arr($user_ids));
        if(!$user_ids){
            return SelfResponse::error('请选择要操作的数据');
        }
        if(\DC\UserCenter\Models\UserBaseModel::where('status',0)->whereIn('member_id',$user_ids)->delete()){
            UserAuthModel::init()->where('status',0)->whereIn('member_id',$user_ids)->delete();
            UserInfoModel::init()->whereIn('member_id',$user_ids)->delete();
            UserWalletModel::init()->whereIn('member_id',$user_ids)->delete();
            return SelfResponse::success('删除会员成功','f_Wap_User_active_list');
        }
        return SelfResponse::error('删除会员失败');

    }

    // 原点升级

    public function upUserLevel(Request $request){

        // 系统 最大级别
        $sys_max_level = config('shop.sys_level');

        $user_id = $request->input('user_id');
        $info = UserBaseModel::init()->find($user_id);

        if($request->isMethod('post')){

            $up_level =  $request->input('up_level');
            if(!$up_level || $up_level < $info->level){
                return SelfResponse::error('升级系统异常，请稍后再试...');
            }

            $now_money = format_rule(json_decode(get_rule('bill_money')))[$info->level][1] ;
            $up_money = format_rule(json_decode(get_rule('bill_money')))[$up_level][1] ;

            if(config('website.up_level_type') == 1){
                $need_money = $up_money ;
            }else{
                $need_money = $up_money - $now_money ;
            }

            if($need_money >$info->wallet->money4 ){
                return SelfResponse::error('升级账户余额不足...');
            }

            if( UserBaseModel::init()->where('member_id',$user_id)->update(['level'=>$up_level]) && UserWalletModel::where('member_id',$user_id)->decrement('money4',$need_money)){

                $params = [
                    'money_type'=>4,
                    'change_type'=>59,
                    'before_money'=>$info->wallet->money4,
                ];
                AccountFlowModel::init()->createFlow($user_id,$need_money,0,$params);

                $regBonus = new RegBonus();
                $regBonus->UpLevelAchievement($user_id,$need_money);
            }

            return SelfResponse::success('升级成功');

        }else{
            //比较级别
            if($info->level < $sys_max_level){
                $next_level = $info['level'] +1;
            }
            return $this->wapRender('user.up_level',[
                'page_title'=>'原点升级',
                'info'=>$info,
                'sys_level'=>$sys_max_level,
                'next_level'=>$next_level ?? 0,
            ]);
        }
    }

    // 平台赠送
    public function giveBonus(Request $request){

        $user_id = $request->input('user_id');

        $bonus_record =BonusRecordModel::init()->where('target_uid',$user_id)->where('bonus_type',42)->where('bonus','>',0)->count();
        if($bonus_record){
            return redirect()->route('f_Wap_User_index');
        }

        $group=BonusRecordModel::max('group');
        if(!$group) {
            $group=1;
        }else{
            $group =$group+1;
        }
        RegBonus::make()->setGroup($group)->award($user_id);
        return redirect()->route('f_Wap_User_index');
    }

}